#!/bin/bash

## This script is meant to be run by neomutt via a timeout-hook.
## It will run ${sync_cmd}, and check/deal a few things:
## * that your gpg key or smart card is cached
## * that ${sync_cmd} isn't already running
## * that you have internet
## TODO: list more things ^?


sync_cmd="mbsync --quiet --all"
#gpg_cached="$({ gpg-connect-agent 'keyinfo --list' /bye 2>/dev/null; gpg-connect-agent 'scd getinfo card_list' /bye 2>/dev/null; } | awk 'BEGIN{CH=0} /^S/ {if($7==1){CH=1}; if($2=="SERIALNO"){CH=1}} END{if($0!=""){print CH} else {print "none"}}')"
gpg_cached="$({ gpg-connect-agent 'keyinfo --list' /bye 2>/dev/null; gpg-connect-agent 'scd getinfo card_list' /bye 2>/dev/null; } | awk 'BEGIN{CH=0; TO=0} /^S/ {if($7==1){CH=1}; {if($4=="T"){TO=1}}; if(TO==1 && $2=="SERIALNO"){CH=1}} END{if($0!=""){print CH} else {print "none"}}')"


## Check for gpg key/smartcard in cache, exit if not.
## see my blog post for a breakdown of the gpg cache check
## https://demu.red/blog/2017/03/how-to-check-if-your-smartcards-gpg-key-is-in-cache-part-3/
if [ "${gpg_cached}" == 0 ]; then
    exit    ## Exit if key not cached
fi


## Exit if ${sync_cmd} already running
if [ "$(pgrep "${sync_cmd%% *}")" ]; then
    exit
fi


## Check for internet
## see https://unix.stackexchange.com/a/190610/39115
test=google.com
if nc -zw1 $test 443 2>/dev/null && echo |openssl s_client -connect $test:443 2>&1 |awk 'handshake && $1 == "Verification" { if ($2=="OK") exit; exit 1 } $1 $2 == "SSLhandshake" { handshake = 1 }'; then
    :   ## noop
else
    exit    ## Exit if no internet
fi


## run ${sync_cmd}
${sync_cmd}
